import router from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router'
/**
 * 前置守卫
 */
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      // 跳转主页
      next('/')
      // next(地址)并没有执行后置守卫
      nProgress.done()
    } else {
      // 判断是否获取过用户信息
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])// 动态添加路由
        // router添加动态路由之后，需要转发一下
        next(to.path)// 目的是让路由拥有信息
      } else {
        next()// 放过
      }
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      next()// 放过
    } else {
      next('/login')// 跳转登录页
      nProgress.done()
    }
  }
})

/**
 * 后置守卫
 */
router.afterEach(() => {
  nProgress.done()
})
